/**
 * @name Fw.FollowLayer
 * @class 浮动层（跟随纵向滚动条）组件
 * @constructor
 * @example
 * @return
 */
Fw.FollowLayer = Fw.extend(Fw.Component, {
    /**
     * 初始化组件
     */
    initComponent : function() {
        Fw.FollowLayer.superclass.initComponent.call(this);
    },
    /**
     * 初始化事件
     */
    initEvents : function() {
        //监听win滚动事件
        $(window).on('scroll', Fw.bind(this.onWinScroll, this));
    },
    /**
     * 初始化HTML模版
     */
    initTpl : function() {
        var id = Fw.id();
        var tpl = [
            '<div id="${id}" class="followlayer ${css}">',
                '<ul id="${id}-body"></ul>',
            '</div>'
        ];
        $('body').append(Fw.template(tpl, {
            id: id,
            css: this.css || ''
        }));
        this.el = $('#' + id);
        this.body = $('#' + id + '-body');
        //
        if(this.style){
            this.el.css(this.style);
        }
        
        //item模版
        var itemTpl = [];
        itemTpl.push('{@each items as item,index}');
        itemTpl.push('<li>');
        Fw.each(this.itemTpl, function(item){
            itemTpl.push(item);
        });
        itemTpl.push('</li>');
        itemTpl.push('{@/each}');
        this.itemTpl = Fw.template(itemTpl);
    },
    /**
     * 载入数据
     */
    loadData: function(data){
        this.data = data;
        //将HTML渲染到页面
        if(data){
            var html = '';
            this.body.html(this.itemTpl.render({
                items: data
            }));
        }
        else{
            this.body.html('');
        }
    },
    /**
     * win滚动时触发
     */
    onWinScroll: function(e){
        if(e){
            Fw.defer(this.onWinScroll, 100, this);
        }
        else{
            var scrollTop = $(window).scrollTop();
            var top = this.initialTop + scrollTop;
            var me = this;
            this.el.stop().animate({
                top: this.scrollTop < scrollTop ? top + 20 : top - 20
            }, 300, function(){
                me.el.animate({
                    top: top
                }, 100, function(){
                    me.scrollTop = scrollTop;
                });
            });
        }
    },
    /**
     * 完成渲染
     */
    finishRender: function(){
        Fw.FollowLayer.superclass.finishRender.call(this);
        this.loadData(this.data);
        //
        this.scrollTop = 0;
        this.initialTop = this.el.offset().top;
        this.onWinScroll(true);
    }
});